package conf;

import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 自动打脚本功能
 * @author zhangcx
 *
 */
public class DBMigrateUtil {

	public static void migrateDB(DataSource ds) {
		String sqlMigrationVersionTable = "schema_version_sherlocky";

		Flyway flyway = new Flyway();
		flyway.setLocations("product");
		flyway.setDataSource(ds);
		flyway.setInitOnMigrate(true);
		//版本所在的表
		flyway.setTable(sqlMigrationVersionTable);
		sqlMigrationVersionTable = flyway.getTable();
		try{
			flyway.migrate();
		}catch(FlywayException ex) {
			//最后一个语句执行出错，则把失败的删掉，以免下次再执行的时候出错
			new JdbcTemplate(ds).update("delete from "+ sqlMigrationVersionTable +" where success = 0");
			throw ex;
		}
	}

}
